package cn.wolfcode.rbac.web.interceptor;

import cn.wolfcode.rbac.common.Constants;
import cn.wolfcode.rbac.common.RequirePermission;
import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.domain.vo.R;
import cn.wolfcode.rbac.utils.JsonUtils;
import cn.wolfcode.rbac.utils.RedisUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            // 先放行处理，后续和跨域有关系
            return true;
        }
        // 1 校验用户合法
        String userId = request.getHeader(Constants.USER_ID);
        Assert.notNull(userId,"非法用户2");
        String employeeJson = redisUtils.get(Constants.LOGIN_EMPLOYEE + userId);
        if (StringUtils.isEmpty(employeeJson)) {
            response.getWriter().write(JsonUtils.toJsonString(R.fail(HttpStatus.UNAUTHORIZED.value(),"认证未通过")));
            return false;
        }
        // 2 校验权限
        Employee employee = (Employee) JsonUtils.fromJson(employeeJson, Employee.class);
        if(employee.isAdmin()) return true;
        String expressionsJson = redisUtils.get(Constants.LOGIN_EXPRESSION + userId);
        if (StringUtils.isEmpty(expressionsJson)){
            return false;
        }
        ObjectMapper mapper = new ObjectMapper();
        List expressions = mapper.readValue(expressionsJson, List.class);


        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequirePermission annotation = handlerMethod.getMethodAnnotation(RequirePermission.class);
        if(annotation == null) return true;
        String expression = annotation.value()[1];
        if(!expressions.contains(expression)) {
            response.getWriter().write(JsonUtils.toJsonString(R.fail(HttpStatus.FORBIDDEN.value(),"授权未通过")));
            return false;
        }
        return true;
    }
}
